package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.util.DateUitls;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.widget.ItemGroup;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AddLessonActivity extends AppCompatActivity implements ItemGroup.ItemOnClickListener{

    private static final String TAG = "AddLessonActivity";
    //private String submitUrl = "http://10.0.2.2:8080/timetable/setClass";
    private String submitUrl = HttpUtils.headerUrl+"timetable/setClass";
    private Context mContext;
    private ItemGroup classNameIG, aNameIG, showAddressIG, classTimeIG,teacherIG,classifyIg,classLenIG,batchNumIG;
    private TextView resultTv;
    private Button backBtn;
    private int xnum;
    private int ynum;
    private int weekday;
    private String classDate;
    private String weekid;
    private int checkNum_classifyClass = -1;
    private int checkNum_classLen = 2;
    private int checkNum = -1;
    private int nextclassNum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_lesson);
        mContext = this;
        initView();
    }

    private void initView() {
        classNameIG = (ItemGroup) findViewById(R.id.className_ig);
        aNameIG = (ItemGroup) findViewById(R.id.id_aName_ig);
        showAddressIG = (ItemGroup) findViewById(R.id.show_address_ig);
        classTimeIG = (ItemGroup) findViewById(R.id.show_classTime_ig);
        teacherIG = (ItemGroup) findViewById(R.id.id_teacher_ig);
        classLenIG = (ItemGroup) findViewById(R.id.classLen_ig);
        classifyIg = (ItemGroup) findViewById(R.id.classify_ig);
        batchNumIG = (ItemGroup) findViewById(R.id.id_batchNum_ig);

        //classLenIG.setItemOnClickListener(this);
        classifyIg.setItemOnClickListener(this);
        resultTv = (TextView) findViewById(R.id.result_tv);
        Intent intent = getIntent();
        xnum = intent.getIntExtra("xnum",0);
        ynum = intent.getIntExtra("ynum",0);
        weekday = intent.getIntExtra("weekday",0);
        classDate = intent.getStringExtra("classDate");
        weekid = intent.getStringExtra("weekid");
        //nextclassNum = intent.getIntExtra("nextclassNum",0);

        /*日期显示*/
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date classdt = null;
        try {
            classdt = format.parse(classDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(classdt);
        classTimeIG.setText(classDate+" "+ DateUitls.formateDay(cal.get(Calendar.DAY_OF_WEEK)));
        showAddressIG.setText(intent.getStringExtra("classAddr"));

        //处理节次
        if (ynum%2 ==0){
            ynum = ynum - 1;
        }
        classLenIG.setText(ynum+"-"+(ynum+1));

        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });
        findViewById(R.id.submit_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提交
                String className = classNameIG.getText();
                String aName = aNameIG.getText();
                String teacherId = teacherIG.getText();
                String batchNum = batchNumIG.getText();
                if (className==null || className.equals("")){
                    Toast.makeText(mContext, "未填写课程名称", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (aName==null || aName.equals("")){
                    Toast.makeText(mContext, "未填写申请人姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (teacherId==null || teacherId.equals("")){
                    Toast.makeText(mContext, "未填写教师教工号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (batchNum ==null || batchNum.equals("")){
                    Toast.makeText(mContext, "未填写实验批次", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (checkNum_classifyClass==-1){
                    Toast.makeText(mContext, "请选择比赛类型", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(checkNum_classLen == -1){
                    Toast.makeText(mContext, "请选择上课时长", Toast.LENGTH_SHORT).show();
                    return;
                }
                int batchNumInt = 0;
                try{
                     batchNumInt = Integer.parseInt(batchNum);
                }catch (Exception e){
                    Toast.makeText(mContext, "实验批次输入不合法", Toast.LENGTH_SHORT).show();
                    return;
                }

                //Toast.makeText(mContext, "\nxnum:"+xnum+"\nynum:"+ynum+"\nweekid:"+weekid+"\nclassDate:"+classDate+"\n", Toast.LENGTH_LONG).show();
                Map<String, String> params = new HashMap<String, String>();
                params.put("lessonName",classNameIG.getText());
                params.put("tid",teacherIG.getText());
                params.put("classNum", String.valueOf(ynum));
                params.put("classLength", String.valueOf(2));
                params.put("weekid", weekid);
                params.put("weekday", String.valueOf(weekday));
                params.put("batchNum", batchNum);
                params.put("classDate",classDate);
                params.put("classClassify", String.valueOf(checkNum_classifyClass));
                params.put("applicationName", aNameIG.getText());
                params.put("lid", String.valueOf(xnum));
                //Toast.makeText(mContext, params.toString(), Toast.LENGTH_LONG).show();
                submitPostData(params, "utf-8");
            }
        });
    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {
            case R.id.classify_ig:
                final String[] items = {"实验","考试","培训","比赛","其他"};
                String titleStr = "选择上课类型";
                showSingleAlertDialogNoBtn(v,items,titleStr,1);
                break;
            /*case R.id.classLen_ig:
                String[] itemsClassLen = new String[nextclassNum-ynum];
                for (int i = 1; i <= nextclassNum - ynum; i++){
                    itemsClassLen[i-1] = i+"节";
                }
                String titleClassLen = "选择上课时长";
                showSingleAlertDialogNoBtn(v,itemsClassLen,titleClassLen,2);
                break;*/
        }
    }

    private AlertDialog singleAlertDialogNoBtn;
    public void showSingleAlertDialogNoBtn(View view, final String[] items, String title,final int thisCheckNumClassify) {


        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setTitle(title);
        switch (thisCheckNumClassify) {
            case 1:
                checkNum = checkNum_classifyClass;
                break;
            case 2:
                checkNum = checkNum_classLen;
                break;
        }
        alertBuilder.setSingleChoiceItems(items, checkNum, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int index) {
                Toast.makeText(mContext, items[index], Toast.LENGTH_SHORT).show();
                checkNum = index;
                switch (thisCheckNumClassify) {
                    case 1:
                        checkNum_classifyClass = index;
                        classifyIg.setText(items[index]);
                        break;
                    case 2:
                        checkNum_classLen = index;
                        classLenIG.setText(items[index]);
                        break;
                }
                singleAlertDialogNoBtn.dismiss();
            }
        });
        singleAlertDialogNoBtn = alertBuilder.create();
        singleAlertDialogNoBtn.show();
    }


    Handler submitHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                int isSuccess = jsonObj.getInt("isSuccess");
                if(isSuccess == 3){
                    Toast.makeText(AddLessonActivity.this, "该教工号不存在，若未注册请先注册", Toast.LENGTH_LONG).show();
                }else if(isSuccess == 0){
                    Toast.makeText(AddLessonActivity.this, "预排课成功", Toast.LENGTH_LONG).show();
                    finish();
                }else if(isSuccess == 1){
                    Toast.makeText(AddLessonActivity.this, "预排课出错", Toast.LENGTH_LONG).show();
                }else if(isSuccess==2){
                    Toast.makeText(AddLessonActivity.this, "预排课失败，刷新查看是否有课程冲突", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Toast.makeText(AddLessonActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
        }
    };

    public void submitPostData(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(submitUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = submitHandler.obtainMessage();
                        msg.obj = text;
                        submitHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }


}
